import logging
import functools
import time

# 配置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')


def limit_calls(threshold):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            if not hasattr(wrapper, 'count'):
                wrapper.count = 0
            wrapper.count += 1

            if wrapper.count > threshold:
                print(f"Function {func.__name__} has been called {threshold} times. Continue the program.")
                
                # 优化：使用更简洁的方式显示倒计时
                for i in range(3, 0, -1):
                    print(f"{i} 秒后程序停止")
                    time.sleep(1)
                exit(0)
            else:    
                # 记录开始时间
                start_time = time.time()
                result = func(wrapper.count, *args, **kwargs)  # 传递调用次数
                # 记录结束时间
                end_time = time.time()  
                elapsed_time = end_time - start_time  # 计算运行时间
                logging.info(f"Function {func.__name__} took {elapsed_time:.4f} seconds to run.")
                
                return result
        
        return wrapper
    return decorator

@limit_calls(threshold=5)
def hello_world(call_number, message):
    logging.info(f"Call {call_number}: {message}")

if __name__ == "__main__":
    for _ in range(7):
        hello_world("Hello world!")  # 传递消息